package com.small.flowable.modules.app.services;

import com.small.flowable.modules.app.dto.rsp.ProcessInstanceRsp;
import lombok.AllArgsConstructor;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 实例
 *
 * @author wangguochao
 */
@Service
@AllArgsConstructor
public class ProcessInstanceService {


    private final RuntimeService runtimeService;

    /**
     * 运行时实例
     */
    public List<ProcessInstanceRsp> getRuntimeProcessInstanceList() {

        List<ProcessInstance> list = runtimeService.createProcessInstanceQuery()
                .orderByStartTime()
                .list();
        List<ProcessInstanceRsp> records = new ArrayList<>();

        list.forEach(obj -> {
            records.add(this.toRsp(obj));
        });
        return records;
    }

    /**
     * 开启流程实例
     *
     * @param processDefinitionKey key
     * @return 实例
     */
    public ProcessInstance startProcessInstance(String processDefinitionKey) {
        return runtimeService.startProcessInstanceByKey(processDefinitionKey);
    }

    /**
     * 输出对象
     *
     * @param processInstance 实例对象
     * @return 实体对象
     */
    public ProcessInstanceRsp toRsp(ProcessInstance processInstance) {
        return ProcessInstanceRsp.builder()
                .isScope(processInstance.isSuspended())
                .processDefinitionId(processInstance.getProcessDefinitionId())
                .processDefinitionName(processInstance.getProcessDefinitionName())
                .processInstanceId(processInstance.getProcessInstanceId())
                .name(processInstance.getName())
                .description(processInstance.getDescription())
                .startTime(processInstance.getStartTime())
                .startUserId(processInstance.getStartUserId())
                .build();
    }

    public ProcessInstanceRsp getByProcessInstanceId(String processInstanceId) {
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        return this.toRsp(processInstance);
    }
}
